﻿''=====================================================================================
''  
Imports TBCC.UserManage
Imports TBCC.UtilityMobile
Public Class MainForm

    Private Shared _pi As ProjectItem = Nothing
    Private Shared WithEvents _ProjectListForm As ProjectListForm
    Private Shared WithEvents _ProjectWebForm As ProjectWebForm

    Private _masterNetID As Byte = 255
    Public Property MasterNetID() As Byte
        Get
            Return _masterNetID
        End Get
        Set(ByVal value As Byte)
            _masterNetID = value
        End Set
    End Property

    Public ReadOnly Property IsOffline() As Boolean
        Get
            Return g_offline
        End Get
    End Property

    Public Shared ReadOnly Property pi() As ProjectItem
        Get
            Return _pi
        End Get
    End Property

    Public Shared ReadOnly Property ProjectList() As Hashtable
        Get
            Return _ProjectListForm.ProjectList
        End Get
    End Property


    ''' <summary>
    ''' 刷新当前工程的信息
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RefeshCurrentProjectInfo()
        If _pi IsNot Nothing Then
            _pi = ProjectService.RefreshCurProjectList(_pi.ProjectID)
        End If
    End Sub

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Me.WindowState = FormWindowState.Maximized
        ' Me.MinimumSize = My.Computer.Screen.WorkingArea.Size
        Me.Refresh()
        Me.WindowState = FormWindowState.Minimized
        Init()

        If My.User.CurrentPrincipal.IsInRole(RoleClass.GetRolename(RoleType.Admin)) = True Then ' 切换到Admin用户
            PanelClient.BackgroundImage = My.Resources.Mainformbackground
        Else
            LoadProjects()
        End If

        'InitBackgroundUpdate()

        '-----------------2008-11-20-----------------
        'InitClientSocket()
        '--------------Add by ZhangTeng--------------

        ''=========================================
 
    End Sub

    Private hs As ShowSelect
    Public Sub RegShowMethod(ByVal method As ShowSelect)
        hs = method
    End Sub

    Private Sub Init()
        Me.ssLogintime.Text = Now.ToString("yyyy-MM-dd HH:mm:ss")
        Me.ssUserName.Text = String.Empty
        Me.ssTip.Text = "尚未连接"
    End Sub


    Private Sub LoadProjects()

        _ProjectListForm = New ProjectListForm()
        AddForm2Panel(_ProjectListForm)
        'TBCC.Data.BackupRestore.ConfigurationManager.ProjectID = ""
        'TBCC.Data.BackupRestore.ConfigurationManager.SetMySqlConnectionString(SqlHelper.GetDBConn)
        'TBCC.Data.BackupRestore.Schedule.GetInstance().Start()
        refreshStatus()
    End Sub

    Private Sub LoadPrjWeb()

        _ProjectWebForm = New ProjectWebForm()
        AddForm2Panel(_ProjectWebForm)

    End Sub

#Region " 菜单栏管理 "

#Region " 系统 ok "

    '[切换用户]
    Private Sub MnuSwitchUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuSwitchUser.Click
        Dim frm As New TBCC.UserManage.LoginForm
        If g_offline = False Then '当前连接已建立
            msg.Show("切换前请挂断当前连接。")
            Exit Sub
        End If

        If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
            If My.User.CurrentPrincipal.IsInRole(RoleClass.GetRolename(RoleType.Admin)) = True Then ' 切换到Admin用户
                CloseProject()
            Else
                If _ProjectListForm Is Nothing Then
                    LoadProjects()
                End If
            End If
            Program.CheckUserRight(Me, Not g_offline)
            refreshStatus()
        End If
    End Sub

    Public Sub SwitchUser()
        mnuDisconnect.PerformClick()
        If My.User.CurrentPrincipal.IsInRole(RoleClass.GetRolename(RoleType.Admin)) = True Then ' 切换到Admin用户
            CloseProject()
        Else
            If _ProjectListForm Is Nothing Then
                LoadProjects()
            End If
        End If
        Program.CheckUserRight(Me, Not g_offline)
        refreshStatus()
    End Sub

    '[修改密码]
    Private Sub mnuChangePassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuChangePassword.Click
        Dim frm As New TBCC.UserManage.ChangePasswordForm()
        frm.ShowDialog()
    End Sub

    '[用户管理]
    Private Sub mnuUserManage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuUserManage.Click
        Dim frm As New TBCC.UserManage.UserManageForm()
        frm.ShowDialog()
    End Sub

    '[退出]
    Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
        ' Me.Close()
        ShowS()
    End Sub

    Private Sub ShowS()
        hs()
        Me.Hide()
    End Sub

#End Region

#Region " 终端管理 TODO "

    'TODO[终端导入]
    Private Sub mnuprjload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


        Dim m_pi As ProjectInfo.CarProjectInfo

        Dim frm As New OpenFileDialog()
        frm.Filter = "工程配置文件(*.cbl)|*.cbl"
        frm.FileName = ""
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim f As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            Dim s As New IO.FileStream(frm.FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
            Try
                m_pi = CType(f.Deserialize(s), ProjectInfo.CarProjectInfo)
                '导入检测本项目中是否包含该工程
                If True = CarProjectService.CheckProject(m_pi.ProId) Then
                    If msg.ShowYesNo("该项目中已经包含该车载信息再次导入会清除之前所有数据,是否继续?") = Windows.Forms.DialogResult.No Then
                        Exit Sub
                    End If
                End If

                If CarProjectService.UpdatePrjDataToDb(m_pi) Then
                    refreshProjectForm()
                    '更新加载车载工程字段值
                    KeyValuePairClass.SetValue1("loadcarproject", 1)
                    msg.Show("工程导入成功")
                Else
                    msg.Show("工程导入失败")

                End If

            Catch ex As Exception
                msg.ShowError(ex.Message)
                Exit Sub
            Finally
                s.Close()
            End Try

        End If

    End Sub

   

    'ok[终端信息管理]
    Private Sub submnu_connectinfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'If g_offline = False Then '当前工程已经连接时不允许配置工程信息
        '    msg.Show("配置工程连接信息前请先断开当前工程连接")
        '    Exit Sub
        'End If

        Dim frm As New ProjectManageForm()
        frm.ShowDialog()

        If frm.Update_Flag = True Then '参数发生修改
            If _ProjectListForm IsNot Nothing Then
                _ProjectListForm.LoadProjects()
            End If
            'LoadProjects()
            'Me.RefeshCurrentProjectInfo() '刷新到当前工程信息变量中(刷新_pi)
        End If
    End Sub



    'NONE[主控地址设置]
    Private Sub mnuHostAddress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'ShowParameterForm(Of HostAddressForm)()
    End Sub



 


#End Region

#Region " 参数设置 ok "



    'NONE[报警铃声设置]
    Private Sub AlarmSoundMnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim frm As New AlarmSoundForm
        'frm.ShowDialog()
    End Sub

    'NONE[温湿度零点偏移标定]
    Private Sub submenu_zerorevise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'ShowParameterForm(Of AIZeroReviseForm)()
    End Sub



    'ok改为数字量[温湿度AI信号值]
    Private Sub submenu_AIread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Me.ShowParameterForm(Of AIZeroReadForm)()
    End Sub

    'NONE[后台上传配置]
    Private Sub mnuBgUploadConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim frm As New BgUploadConfigForm()
        'frm.ShowDialog()
    End Sub

#End Region

#Region " 数据分析 "

    'TODO[主工程图]
    Private Sub mnuMain_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMain.Click
        'refreshProjectForm()
        If _ProjectListForm IsNot Nothing Then
            _ProjectListForm.LoadProjects()
        End If
    End Sub

    'NONE[实时报警查询]
    Private Sub mnuRealtimeAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRealtimeAlarm.Click
        'ShowParameterForm(Of RealAlarmForm)()
    End Sub

    'NONE[历史报警查询]
    Private Sub mnuHistoryAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistoryAlarm.Click
        'Dim frm As New HDAlarmForm
        'frm.Owner = Me
        'frm.ShowDialog()
    End Sub

    

#End Region



#Region " 连接 "

    'TODO[连接]
    Private Sub mnuReConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuReConnect.Click
        'Dim frm As New TerminalConnectForm()
        Dim frm As New ConnectForm()
        '  frm.ShowDialog()
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then

            SetConnect()

            Program.CheckUserRight(Me, Not g_offline)
            Me.tsbLink.Text = "断开"
            Me.tsbLink.Image = TBCC.Device240System.My.Resources.断开

        Else

            SetDisconnect()

        End If
        ''Me.Cursor = Cursors.WaitCursor
        ''Me.Connect()
        ''Me.Cursor = Cursors.Default
    End Sub

    'TODO[断开]
    Private Sub mnuDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDisconnect.Click

        TCP_IsCloseHandler = True

        Me.SetDisconnect()

        Program.CheckUserRight(Me, Not g_offline)
        Me.tsbLink.Text = "连接"
        Me.tsbLink.Image = TBCC.Device240System.My.Resources.连结


        Try
            COMHelper.Instance.Close()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        ''刷新工程界面数据
        'mnuMain.PerformClick()

    End Sub

    'TODO[历史数据上传]
    Private Sub mnuHDUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHDUpload.Click
        'ShowParameterForm(Of DataUploadForm)()
    End Sub

    'TODO[历史报警上传]
    Private Sub mnuHAUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHAUpload.Click
        'ShowParameterForm(Of AlarmDataUploadForm)()
    End Sub

    Private Sub mnuScanTerminal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuScanTerminal.Click
        Dim frm As New TerminalForm()
        frm.Show()
        'If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
        '    If _ProjectListForm IsNot Nothing Then
        '        _ProjectListForm.LoadProjects()
        '    End If
        'End If
    End Sub

#End Region

#Region " 数据库维护 "

    'TODO[数据备份设置]
    Private Sub mnuBackup2Path_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim frm As New DBBackupPathConfigForm
        'frm.ShowDialog()
        'Dim cm As TBCC.Data.BackupRestore.ConfigurationManager = New TBCC.Data.BackupRestore.ConfigurationManager()
        'Dim str As String = readConfig("mysqldir") + "/bin"
        'str = str.Replace("\", "/")
        ''msg.Show(str)
        'cm.SaveConfig(str)
        'cm.ShowSettingForm()
    End Sub
    Private Function readConfig(ByVal strkey As String) As String

        Dim strreturn As String
        Dim appreader As Configuration.AppSettingsReader = New Configuration.AppSettingsReader()
        Try
            strreturn = appreader.GetValue(strkey, Type.GetType("System.String")).ToString()
        Catch ex As Exception
            strreturn = ex.Message.ToString()
        Finally
            appreader = Nothing
        End Try
        Return strreturn
    End Function

   


    'TODO[数据清理工具]
    Private Sub mnuDbClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'If g_offline = False Then
        '    msg.Show("数据清除前请先挂断连接")
        '    Exit Sub
        'End If
        ' ShowParameterForm(Of DBClearForm)()
    End Sub

#End Region

#Region " 帮助 "

    'TODO[帮助]
    Private Sub mnuHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHelpfile.Click
        Dim helpFile As String
        helpFile = Application.StartupPath + "\help.chm"
        If System.IO.File.Exists(helpFile) Then
            System.Diagnostics.Process.Start(helpFile)
        Else
            '提示找不到帮助文件()
            msg.Show("找不到帮助文件 help.chm ")
        End If
    End Sub

    'TODO[关于对话框]
    Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAbout.Click
        Dim frm As New AboutBox
        frm.ShowDialog()
    End Sub

#End Region

#End Region

#Region " DataGridView操作 "

    ''创建新行
    'Private Function GetNewRow() As DataGridViewRow
    '    Dim row As New DataGridViewRow()
    '    Dim cell As DataGridViewCell

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    cell = New DataGridViewTextBoxCell()
    '    row.Cells.Add(cell)

    '    Return row
    'End Function

    '
    Private Sub dgvProjectList_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
        'Dim row As DataGridViewRow
        'row = _ProjectListForm.dgvProjectList.Rows(e.RowIndex)
        '_pi = row.Tag
        'Program.CheckUserRight(Me, _pi.IsLocalOnline)
    End Sub

#End Region

    'Friend Shared Sub SetProjectItem(ByVal pi As ProjectItem)
    '    _pi = pi
    'End Sub



    ''' <summary>
    ''' 初始化串口
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function InitCOM() As Boolean
        Dim com As String
        com = _pi.ComNumber.ToString()

        If com = "" Then
            msg.Show("请先配置串口")
            Return False
        End If

        If COMHelper.Instance.InitSerialPort(com.Replace("COM", ""), IO.Ports.Parity.Even) Then
            Return DirectConnect()
        Else
            msg.ShowError("初始化串口失败,请检查串口配置")
            Return False
        End If
    End Function

    ''' <summary>
    ''' 设置无法连接状态
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetDisconnect()
        g_offline = True
        Me.ssTip.ForeColor = Color.Red
        Me.ssTip.Text = "连接断开"
    End Sub

    ''' <summary>
    ''' 设置连接状态
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetConnect()
        g_offline = False
        Me.ssTip.ForeColor = Color.Black
        Me.ssTip.Text = "连接建立"
    End Sub
    'ok
    ''' <summary>
    ''' 与下位机GSM口建立直连
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function DirectConnect() As Boolean
        Dim strResult As String

        For i As Integer = 0 To 2

            strResult = COMHelper.Instance.WriteCommand(UtilityClass.GetAuthCodeByte(_pi.AuthCode), 10, 10000)
            If strResult.IndexOf("AT^AUTH=OK") >= 0 Then
                Return True
            Else
                msg.ShowError("与下位机的连接鉴权失败。")
                Return False
            End If

            System.Threading.Thread.Sleep(1000)
            Application.DoEvents()
        Next

        msg.ShowError("无法建立于下位机的连接")

        Return False
    End Function

    '-----------------2008-11-20-----------------
    '--------功能：初始Socket断线处理方法--------
    Private Sub InitClientSocket()
        COMHelper.Instance.OnDisconnect = AddressOf TCP_OnDisconnect
    End Sub
    Private Sub TCP_OnDisconnect(ByVal sender As Object, ByVal e As TBCC.UtilityMobile.TCP.DisconnectArgs)
        If Me.InvokeRequired Then
            Me.Invoke(New MethodInvoker(AddressOf TCP_OnDisconnectMethod))
        Else
            TCP_OnDisconnectMethod()
        End If
    End Sub
    Private Sub TCP_OnDisconnectMethod()
        'System.IO.File.AppendAllText("./ConnectInfo.Log", _
        '                                    String.Format("{0} =====> 连接类型:{1}, {2}" & vbCrLf, Now, MainForm.pi.connectType, "网络连接已经断开"), _
        '                                    System.Text.Encoding.UTF8)
        'mnuDisconnect.PerformClick()
        ''mnuReConnect.PerformClick()
        'Connect(True)
        ''msg.ShowError("网络连接已经断开")
        TCP_Connect()
    End Sub
    '-------------- 2009-03-16 ---------------
    Dim TCP_isConnected As Boolean = False
    Dim TCP_IsConnecting As Boolean = False
    Dim TCP_IsForceClose As Boolean = False
    Dim TCP_IsCloseHandler As Boolean = False
    Dim TCP_ConnectCount As UInt32 = 0

    Private Sub TCP_Connect()
        If TCP_IsConnecting = True Then
            'TCP_IsForceClose = True
            'COMHelper.Instance.Close(True)
            'TCP_IsConnecting = False
        Else

            TCP_isConnected = False
            TCP_IsCloseHandler = False


            Dim handler As New CrossAppDomainDelegate(AddressOf _TCP_Connect)
            handler.BeginInvoke(New System.AsyncCallback(AddressOf TCP_Connect_Callback), Nothing)

        End If
    End Sub

    Private Sub _TCP_Connect()
        If TCP_IsConnecting = False Then
            TCP_IsConnecting = True

            Do While TCP_IsCloseHandler = False AndAlso TCP_isConnected = False
                TCP_ConnectCount += 1
                SetStatusBar(False, Color.Red, String.Format("正在重连({0})", TCP_ConnectCount))

                TCP_isConnected = COMHelper.Instance.InitSocket(_pi.Phone, _pi.ComNumber)

                If TCP_isConnected = True Then
                    TCP_isConnected = False

                    Dim strResult As String
                    strResult = COMHelper.Instance.WriteCommand(UtilityClass.GetAuthCodeByte(_pi.AuthCode), 10, 10000)
                    If strResult.IndexOf("AT^AUTH=OK") >= 0 Then
                        TCP_isConnected = True
                        '_isAuthFail = False
                    Else
                        '_isAuthFail = True
                    End If

                End If
            Loop

            TCP_IsConnecting = False
        End If
    End Sub

    Private Sub TCP_Connect_Callback(ByVal ar As System.IAsyncResult)
        If TCP_IsConnecting = False Then
            If Me.InvokeRequired = True Then
                Me.Invoke(New CrossAppDomainDelegate(AddressOf _TCP_Connect_Callback), Nothing)
            Else
                _TCP_Connect_Callback()
            End If
        End If
    End Sub
    Private Sub _TCP_Connect_Callback()
        TCP_ConnectCount = 0

        If TCP_isConnected = True Then
            SetStatusBar(True, Color.Black, "连接建立")

            Program.CheckUserRight(Me, Not g_offline)

        End If
    End Sub

    Private Sub SetStatusBar(ByVal online As Boolean, ByVal statusColor As Color, ByVal statusText As String)
        Dim obj As Object = New Object() {online, statusColor, statusText}
        If Me.InvokeRequired = True Then
            Me.Invoke(New Action(Of Object)(AddressOf _SetStatusBar), obj)
        Else
            _SetStatusBar(obj)
        End If
    End Sub
    Private Sub _SetStatusBar(ByVal obj As Object)
        g_offline = Not obj(0)
        Me.ssTip.ForeColor = obj(1)
        Me.ssTip.Text = obj(2)
    End Sub
    '--------------Add by ZhangTeng--------------



    'ok
    ''' <summary>
    ''' 状态栏时间更新
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If g_tt Then
            Timer1.Stop()
        End If
        Me.ssLogintime.Text = Now.ToString("  yyyy-MM-dd HH:mm:ss")
    End Sub



    'ok
    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        Timer2.Stop()

        Me.MenuStrip1.Enabled = False
        Me.Cursor = Cursors.WaitCursor

        If g_IsProjectDataRead Then
            Timer2.Start()
            Exit Sub
        End If


        Dim obj As Object = System.Activator.CreateInstance(_t)

        Me.MenuStrip1.Enabled = True
        Me.Cursor = Cursors.Default

        g_busy = True
        CType(obj, Form).ShowDialog()
        g_busy = False
    End Sub

    'ok
    ''' <summary>
    ''' 连接控制器
    ''' </summary>
    ''' <remarks></remarks>
    'Private Sub Connect()
    '    Connect(False)
    'End Sub
    'Private Sub Connect(ByVal isRetry As Boolean)

    '    COMHelper.ConnectType = _pi.ConnectType

    '    Me.MenuStrip1.Cursor = Cursors.WaitCursor

    '    If _pi.ConnectType = 1 Then
    '        '直连 
    '        If InitCOM() = False Then
    '            SetDisconnect()
    '            Me.MenuStrip1.Cursor = Cursors.Default
    '            Exit Sub
    '        End If
    '    ElseIf _pi.ConnectType = 0 Then
    '        '拨号
    '        Dim frm As New DialForm("COM" & _pi.ComNumber.ToString(), _pi.Phone)
    '        If frm.ShowDialog <> Windows.Forms.DialogResult.OK Then
    '            SetDisconnect()
    '            Me.MenuStrip1.Cursor = Cursors.Default
    '            Exit Sub
    '        End If
    '    Else
    '        'TCP/IP
    '        If TCP_IsConnecting = False Then
    '            Dim frm As New TcpConnectForm(isRetry)
    '            If frm.ShowDialog() <> Windows.Forms.DialogResult.OK Then
    '                SetDisconnect()
    '                Me.MenuStrip1.Cursor = Cursors.Default
    '                Exit Sub
    '            End If
    '        End If
    '    End If

    '    SetConnect()

    '    Program.CheckUserRight(Me, Not g_offline)

    '    Me.MenuStrip1.Cursor = Cursors.Default

    'End Sub


    'ok
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        'If msg.ShowYesNo("是否要退出？") = Windows.Forms.DialogResult.Yes Then
        '    MyBase.OnClosing(e)
        '    System.Environment.Exit(0)
        'Else
        '    e.Cancel = True
        'End If
        e.Cancel = True
        ShowS()
    End Sub

    'ok
    ''' <summary>
    ''' 将表单添加到PanelClient中
    ''' </summary>
    ''' <param name="frm"></param>
    ''' <remarks></remarks>
    Private Sub AddForm2Panel(ByVal frm As ProjectListForm)
        '隐藏PanelClient内的其它窗体
        For Each c As Form In Me.PanelClient.Controls
            c.Visible = False
        Next

        ' AddHandler frm.ProjectSelected, AddressOf dgvProjectList_RowEnter
        frm.TopLevel = False
        frm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        frm.Dock = DockStyle.Fill
        frm.Parent = Me.PanelClient
        frm.Show()
    End Sub

    Private Sub AddForm2Panel(ByVal frm As ProjectWebForm)
        frm.TopLevel = False
        frm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        frm.Dock = DockStyle.Fill
        frm.Parent = Me.PanelClient
        frm.WebBrowser.Navigate(My.MySettings.Default.PrjWebURL)
        frm.Show()
    End Sub

    'ok
    Private _t As Type

    ''' <summary>
    ''' 显示参数设置界面
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <remarks></remarks>
    Friend Sub ShowParameterForm(Of T As {Form, New})()
        While g_IsProjectDataRead
            _t = GetType(T)
            Me.Timer2.Start()
            Exit Sub
        End While

        '设置g_busy状态为True,停止实时数据的刷新
        g_busy = True

        Try
            Dim frm As New T()
            frm.ShowDialog()
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        '参数设置界面关闭后,设置g_busy状态为False,开始实时数据的刷新
        g_busy = False
    End Sub

    'ok
    ''' <summary>
    ''' 关闭所有MDI子窗体
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CloseAllForms()

        For Each frm As Form In Me.PanelClient.Controls
            If frm.GetType Is GetType(ProjectListForm) Then
                frm.Close()
                _ProjectListForm = Nothing
            ElseIf TypeOf frm Is ProjectWebForm Then
                frm.Close()
                _ProjectWebForm = Nothing
            End If
        Next
        Me.PanelClient.Controls.Clear()
    End Sub

    Private Sub CloseForm(Of T)()
        For Each frm As Form In Me.PanelClient.Controls
            If TypeOf frm Is T Then
                Me.PanelClient.Controls.Remove(frm)
                frm.Close()
                If TypeOf frm Is ProjectWebForm Then
                    _ProjectWebForm = Nothing
                End If
                Exit For
            End If
        Next
    End Sub

    Private Sub CloseProject()

        CloseAllForms()
        _pi = Nothing

        PanelClient.BackgroundImage = My.Resources.Mainformbackground

        'Me.ssCurrentForm.Text = ""

    End Sub

    Private Sub HideForm(Of T)()
        For Each frm As Form In Me.PanelClient.Controls
            If TypeOf frm Is T Then
                frm.Hide()
            End If
        Next
    End Sub

    Private Sub ShowForm(Of T)()
        For Each frm As Form In Me.PanelClient.Controls
            If TypeOf frm Is T Then
                frm.Show()
            End If
        Next
    End Sub

    Private Sub refreshStatus()
        'Me.ssTip.Text = "就绪"
        'Me.ssCurrentForm.Text = ""
        Me.ssLogintime.Text = Now.ToString("yyyy-MM-dd HH:mm:ss")
        Me.ssUserName.Text = String.Format("当前用户：{0}", TBCC.UserManage.User.Instance.uName)
    End Sub

    Private Sub Timer_HistAlarmbackground_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Timer_HistAlarmbackground.Stop()
        'BackgroundAlarmData.Instance.Start()
    End Sub

    Private Sub Timer_HistDatabackground_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Timer_HistDatabackground.Stop()
        'BackgroundHistorydata.Instance.Start()
    End Sub

    Public Sub refreshProjectForm()
        CloseAllForms()
        AddForm2Panel(New ProjectListForm)
    End Sub

    Private Declare Function CreateDC Lib "gdi32.dll" Alias "CreateDCA" (ByVal lpszDriver As String, ByVal lpszDevice As String, ByVal lpszOutput As String, ByVal lpInitData As IntPtr) As IntPtr
    Private Declare Function BitBlt Lib "GDI32" (ByVal hdcDest As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As Integer) As Boolean

    Public Function capture_projectImage(ByVal Rec As Rectangle, ByVal filename As String) As Boolean

        Try

            Dim ScreenTempHdc As IntPtr = CreateDC("DISPLAY", Nothing, Nothing, CType(Nothing, IntPtr))

            Dim ScreenGraph As Graphics = Graphics.FromHdc(ScreenTempHdc)

            '创建一个新的Graphics对象 

            Dim bmpOrigin As Bitmap = New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, ScreenGraph)

            '根据屏幕大小创建一个相同大小的Bitmap 

            Dim OriginGraph As Graphics = Graphics.FromImage(bmpOrigin)

            Dim ScreenHdc As IntPtr = ScreenGraph.GetHdc() '获取屏幕的句柄 

            Dim bmpOriginHdc As IntPtr = OriginGraph.GetHdc() '获取位图的句柄 　　 

            BitBlt(bmpOriginHdc, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, ScreenHdc, 0, 0, 13369376) '把当前屏幕复制到位图中 

            ScreenGraph.ReleaseHdc(ScreenHdc) '释放屏幕句柄 

            OriginGraph.ReleaseHdc(bmpOriginHdc) '释放位图句柄 

            '仅将屏幕中的工程数据部分图形保存
            Dim bmpNew As New Bitmap(Rec.Width, Rec.Height, OriginGraph)
            Dim ee As Graphics = Graphics.FromImage(bmpNew)
            Dim destRect As New Rectangle(0, 0, Rec.Width, Rec.Height)
            Dim srcRect As New Rectangle(Rec.X, Rec.Y, Rec.X + Rec.Width, Rec.Y + Rec.Height)
            ee.DrawImage(bmpOrigin, destRect, srcRect, GraphicsUnit.Pixel)

            bmpNew.Save(filename, Drawing.Imaging.ImageFormat.Jpeg)

        Catch ex As Exception
            Return False
        End Try

        Return True

    End Function




    Private Sub tsbAlarm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        mnuRealtimeAlarm.PerformClick()
    End Sub

    Private Sub tsbHistCurve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbHistCurve.Click
        'mnuHistoryDataCurve.PerformClick()
        '  tsmiHisDataQuery.PerformClick() 
        'HDStartStopCarForm()
        'Dim frm As New ParSetValueForm
        'frm.ShowDialog()
        MenuDevadminItem.PerformClick()
    End Sub

    Private Sub tsbDataUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        mnuHDUpload.PerformClick()
    End Sub

    Private Sub tsbPrjWeb_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbPrjWeb.Click
        Me.mnuMain.Enabled = False
        Me.tsbMain.Enabled = False
        Me.tsbPrjWeb.Enabled = False
        Me.tsbPrjWeb.Visible = False


        'CloseAllForms()
        'LoadPrjWeb()
        HideForm(Of ProjectListForm)()
        LoadPrjWeb()
        'ShowForm(Of ProjectWebForm)()
    End Sub

    Private Sub tsbPrjList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.mnuMain.Enabled = True
        Me.tsbMain.Enabled = True

        Me.tsbPrjWeb.Enabled = True
        Me.tsbPrjWeb.Visible = True

        'CloseAllForms()
        'LoadProjects()
        CloseForm(Of ProjectWebForm)()
        'HideForm(Of ProjectWebForm)()
        ShowForm(Of ProjectListForm)()
    End Sub

    Private Sub submenu_prjimage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub


    Private Sub MenuDevadminItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuDevadminItem.Click
        Dim gp As System.Security.Principal.GenericPrincipal
        gp = My.User.CurrentPrincipal
        Dim frm As New D240SetItemForm(gp)
        frm.ShowDialog()
        If frm.IsModified = True Then '参数发生修改
            refreshProjectForm()
            Program.CheckUserRight(Me, False) '修改当前菜单状态
        End If
       
    End Sub

   

    Private Sub MnuDbRevert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim br As TBCC.Data.BackupRestore.Restore = New TBCC.Data.BackupRestore.Restore
        'br.DoWork(TBCC.Data.BackupRestore.Schedule.GetInstance().Setting)
    End Sub

    Public Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Sub tsbReturn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbReturn.Click
        ShowS()
    End Sub


    Private Sub HisDatastat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HisDatastat.Click
        'mnuHistDataDoc.PerformClick()
        'Dim frm As New SetItemValueForm
        'frm.ShowDialog()
        MenuWebAddItem.PerformClick()
    End Sub

    Private Sub MenuWebAddItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim frm As New DeviceSetForm
        frm.ShowDialog()
    End Sub

    
    Private Sub tsbMain_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbMain.Click
        mnuRealtimeData.PerformClick()
    End Sub

    Private Sub mnuRealtimeData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRealtimeData.Click
        Dim frm As New ParSetValueForm
        frm.ShowDialog()
    End Sub

    Private Sub mnuHisStartup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHisStartup.Click

    End Sub

    Private Sub mnuHistoryDataCurve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistoryDataCurve1.Click
        Dim frm As New SetItemValueForm
        frm.ShowDialog()
    End Sub

    Private Sub peSetItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles peSetItem.Click
        mnuHistoryDataCurve.PerformClick()
    End Sub

    Private Sub tsbLink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbLink.Click
        If Me.mnuReConnect.Enabled Then
            Me.mnuReConnect.PerformClick()
        Else
            Me.mnuDisconnect.PerformClick()
        End If
    End Sub

    Private Sub MenuWebAddItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuWebAddItem.Click
        Dim frm As New DeviceSetForm
        frm.ShowDialog()
    End Sub

    Private Sub mnuHistoryDataCurve_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHistoryDataCurve.Click
        Dim frm As New SetItemValueForm
        frm.ShowDialog()
    End Sub
End Class
